<template>
  <el-card style="text-align:left">
    <div slot="header" class="clearfix">
      <el-steps :active="active" finish-status="success" align-center>
        <el-step title="填写商品基本信息"></el-step>
        <el-step title="填写商品属性"></el-step>
        <el-step title="设置商品库存"></el-step>
      </el-steps>
    </div>
    <div>
      <!--第一步表单-->
      <el-form v-if="this.active==0" :model="form0" :rules="rules" ref="form0" label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="form0.name"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="categories">
          <el-cascader
            ref="categoryRef"
            v-model="form0.categories"
            :options="categoryOptions"
            @change="categoryChange"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="副标题" prop="subTitle">
          <el-input v-model="form0.subTitle" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="商品品牌" prop="brand">
          <el-input v-model="form0.brand"></el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input v-model="form0.description" type="textarea" :rows="2"></el-input>
        </el-form-item>
        <el-form-item label="商品货号" prop="productNo">
          <el-input v-model="form0.productNo"></el-input>
        </el-form-item>
        <el-form-item label="销售价" prop="salePrice">
          <el-input v-model="form0.salePrice"></el-input>
        </el-form-item>
        <el-form-item label="市场价" prop="marketPrice">
          <el-input v-model="form0.marketPrice"></el-input>
        </el-form-item>
        <el-form-item label="计件单位" prop="unit">
          <el-input v-model="form0.unit"></el-input>
        </el-form-item>
      </el-form>

      <!--第二步表单-->
      <el-form
        v-show="this.active==1"
        :model="form1"
        :rules="rules"
        ref="form1"
        label-width="100px"
      >
        <el-form-item label="商品图片" prop="images">
          <uploadImage :uploadFiles="uploadFiles" />
        </el-form-item>

        <el-form-item label="规格参数" prop="detail">
          <el-tabs v-model="descactive" type="card">
            <el-tab-pane label="电脑端详情" name="descpc">
              <div id="editorpc"></div>
            </el-tab-pane>
            <el-tab-pane label="移动端详情" name="desch5">
              <div id="editorh5"></div>
            </el-tab-pane>
          </el-tabs>
        </el-form-item>
      </el-form>
      <!--第三步表单-->
      <el-form v-if="this.active==2" :model="form2" :rules="rules" ref="form2" label-width="100px">
        <el-form-item label="商品类型" prop="kind">
          <el-select v-model="form2.kind" placeholder="请选择" @change="pkindchange">
            <el-option v-for="item in pkinds" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品规格" style="width:40%;">
          <div v-for="attr in attrs" :key="attr.id">
            <p style="margin:0px;padding:0px">{{attr.name}}:</p>
            <el-checkbox-group v-model="attr.checklist" size="small">
              <el-checkbox v-for="item in attr.values" :key="item" :label="item"></el-checkbox>
            </el-checkbox-group>
          </div>
        </el-form-item>
        <el-form-item label="库存">
          <el-button type="primary" @click="genStoreInfo">生成库存</el-button>
          <el-table :data="kindTableData" border style="width: 100%">
            <el-table-column
              :prop="item.name"
              :label="item.name"
              v-for="item in kindTableHeader"
              :key="item.name"
            ></el-table-column>
            <el-table-column prop="price" label="价格">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price" placeholder="价格"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="storeNum" label="库存">
              <template slot-scope="scope">
                <el-input v-model="scope.row.storeNum" placeholder="库存"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="warnNum" label="预警值">
              <template slot-scope="scope">
                <el-input v-model="scope.row.warnNum" placeholder="预警值"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="sku" label="sku">
              <template slot-scope="scope">
                <el-input v-model="scope.row.sku" placeholder="sku"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click.native.prevent="deleKindRow(scope.$index)"
                >移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </div>
    <div style="text-align:center">
      <el-button type="primary" v-show="buttonPre" @click="foward()">上一步</el-button>
      <el-button type="primary" v-show="buttonNext" @click="next()">下一步</el-button>
      <el-button type="primary" v-show="buttonSub" @click="sub()">提交</el-button>
    </div>
  </el-card>
</template>

<script>
import {
  categorylist,
  productModify,
  productkinds,
  attributeListView,
  productLoad
} from "@/libs/api.js";
import Editor from "wangeditor";
import uploadImage from "@/components/upload/UploadImage.vue";
export default {
  components: {
    uploadImage
  },
  data() {
    return {
      active: 0,
      //显示
      buttonPre: false,
      buttonNext: true,
      buttonSub: false,
      form0: {
        name: "",
        categoryId: "",
        categories: "",
        subTitle: "",
        brand: "",
        description: "",
        productNo: "",
        salePrice: "",
        marketPrice: "",
        unit: ""
      },
      form1: {
        images: "",
        detail: { detailpc: "pc", detailh5: "h5" }
      },
      uploadFiles: [],
      form2: {
        kind: ""
      },
      categoryOptions: [],
      descactive: "descpc",
      pkinds: [],
      attrs: [],
      kindTableData: [],
      kindTableHeader: [],
      productId: "",
      rules: {
        name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        categoryId: [
          { required: true, message: "请选择商品分类", trigger: "change" }
        ],
        subTitle: [
          { required: true, message: "请输入商品副标题", trigger: "blur" },
          { min: 3, max: 30, message: "长度在 3 到 30 个字符", trigger: "blur" }
        ],
        brand: [{ required: true, message: "请输入商品品牌", trigger: "blur" }],
        description: [
          { required: true, message: "请输入商品描述", trigger: "blur" }
        ],
        salePrice: [
          { required: true, message: "请输入商品销售价", trigger: "blur" },
          {
            pattern: /^[1-9]\d*$|^[0-9]+(.[0-9]{1,2})?$/,
            message: "请输入正确的价格",
            trigger: "blur"
          }
        ],
        marketPrice: [
          { required: true, message: "请输入商品市场价", trigger: "blur" },
          {
            pattern: /^[1-9]\d*$|^[0-9]+(.[0-9]{1,2})?$/,
            message: "请输入正确的价格",
            trigger: "blur"
          }
        ],
        unit: [
          { required: true, message: "请输入商品计件单位", trigger: "blur" }
        ]
      }
    };
  },

  methods: {
    next() {
      this.$refs["form" + this.active].validate(valid => {
        if (valid) {
          if (this.active == 2) {
            return;
          } else {
            this.active++;
          }
          if (this.active == 2) {
            this.buttonSub = true;
            this.buttonNext = false;
          }
          this.buttonPre = true;
        } else {
          this.$util.errorMsg("form valid error!");
          return false;
        }
      });
    },
    foward() {
      if (this.active == 0) {
        return;
      } else {
        this.active--;
      }
      if (this.active == 0) {
        this.buttonPre = false;
      }
      this.buttonSub = false;
      this.buttonNext = true;
    },
    //商品信息整体提交
    sub() {
      let fileList = this.uploadFiles;
      let param = new FormData();
      param.append("productId", this.productId);
      //封装第一步数据
      for (var key in this.form0) {
        param.append(key, this.form0[key]);
      }
      //封装第二步数据
      if (fileList && fileList.length > 0) {
        let oldFiles = "";
        for (var i = 0; i < fileList.length; i++) {
          if (fileList[i].status != "success") {
            param.append("file", fileList[i].raw);
          } else {
            oldFiles += ";" + fileList[i].name;
          }
        }
        if (oldFiles.length > 0) {
          oldFiles = oldFiles.substring(1);
          param.append("oldFiles", oldFiles);
        }
      }
      param.append("detailpc", this.form1.detail.detailpc);
      param.append("detailh5", this.form1.detail.detailh5);
      //封装第三步
      param.append("kindid", this.form2.kind);
      param.append("productDetail", JSON.stringify(this.kindTableData));
      productModify(param).then(res => {
        this.$util.success();
        if (fileList && fileList.length > 0) {
          for (var i = 0; i < fileList.length; i++) {
            fileList[i].status == "success";
          }
        }
      });
    },
    //下拉分类change
    categoryChange(item) {
      if (item) {
        this.form0.categoryId = this.$refs[
          "categoryRef"
        ].getCheckedNodes()[0].data.id;
      }
    },
    setEditor(id, value) {
      this.editor = new Editor("#" + id);
      this.editor.customConfig.uploadImgShowBase64 = true; // base 64 存储图片
      this.editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024; //图片大小3M
      this.editor.customConfig.uploadImgMaxLength = 5; //最大五张
      let ref = this;
      this.editor.customConfig.onchange = function(html) {
        // html 即变化之后的内容
        // ref.$emit('onchange', html);
        ref.$emit("input", html);
        if (id == "editorpc") {
          ref.form1.detail.detailpc = html;
        } else {
          ref.form1.detail.detailh5 = html;
        }
      };
      this.editor.create();
      if (value) {
        this.editor.txt.html(value);
      }
    },
    //生成库存信息
    genStoreInfo() {
      let arrs = [];
      this.kindTableHeader = [];
      this.kindTableData = [];
      if (this.attrs && this.attrs.length > 0) {
        for (var i = 0; i < this.attrs.length; i++) {
          if (this.attrs[i].checklist && this.attrs[i].checklist.length > 0) {
            arrs.push(this.attrs[i].checklist);
            this.kindTableHeader.push(this.attrs[i]);
          }
        }
        let results = [];
        let temp = [];
        this.doExchange(arrs, 0, temp, results);
        if (results && results.length > 0) {
          for (var i = 0; i < results.length; i++) {
            let temp = {};
            temp.price = this.form0.salePrice;
            temp.storeNum = "100";
            temp.warnNum = "10";
            temp.sku = this.form0.productNo;
            let attrArray = results[i].split(";");
            let kindAttrs = "";
            let kindNames = "";
            let attrs = "";
            for (var j = 0; j < this.kindTableHeader.length; j++) {
              if (this.kindTableHeader[j]) {
                temp[this.kindTableHeader[j].name] = attrArray[j];
                kindAttrs +=
                  ";" + (this.kindTableHeader[j].name + ":" + attrArray[j]);
                kindNames += ";" + this.kindTableHeader[j].name;
                attrs += ";" + attrArray[j];
              }
            }
            if (kindAttrs.length > 0) {
              kindAttrs = kindAttrs.substring(1);
              kindNames = kindNames.substring(1);
              attrs = attrs.substring(1);
            }

            temp.kindAttrs = kindAttrs;
            temp.kindNames = kindNames;
            temp.attrs = attrs;
            this.kindTableData.push(temp);
          }
        }
      }
    },
    //删除记录
    deleKindRow(index) {
      this.kindTableData.splice(index, 1);
    },
    //排列组合
    doExchange(arr, index, temp, results) {
      if (arr && arr.length > 0) {
        for (var i = 0; i < arr[index].length; i++) {
          temp[index] = arr[index][i];
          if (index != arr.length - 1) {
            this.doExchange(arr, index + 1, temp, results);
          } else {
            results.push(temp.join(";"));
          }
        }
      }
    },
    //商品属性选择
    pkindchange(value) {
      attributeListView(value).then(res => {
        if (res && res.length > 0) {
          for (var i = 0; i < res.length; i++) {
            res[i].checklist = [];
          }
          this.attrs = res;
        }
      });
    }
  },
  mounted() {
    //分类
    categorylist().then(res => {
      this.categoryOptions = res;
      if (this.$route.query.id) {
        this.productId = this.$route.query.id;
        productLoad(this.productId).then(res => {
          var newObj = Object.assign(this.form0, res.product);
          this.form0 = newObj;
          delete this.form0["detailpc"];
          delete this.form0["detailh5"];
          if (res.product.categories) {
            this.form0.categories = res.product.categories.split(",");
          }

          if (res.product.images) {
            let images = res.product.images.split(";");
            for (var i = 0; i < images.length; i++) {
              var file = {
                name: images[i],
                url: this.$http.baseUrl + "/file/show/" + images[i],
                statuss:"success"
              };
              this.uploadFiles.push(file);
            }
          }
          this.form1.detail.detailpc = res.product.detailpc;
          this.form1.detail.detailh5 = res.product.detailh5;
          this.form2.kind = res.product.kindId;
          let tempAttrs = [];
          let attrNames="";
          let attrNameValue={};
          if (res.details && res.details.length > 0) {
            for (var i = 0; i < res.details.length; i++) {
              var temp = {};
              temp.price = res.details[i].price;
              temp.storeNum = res.details[i].storeNum;
              temp.warnNum = res.details[i].warnNum;
              temp.sku = res.details[i].sku;
              temp.kindAttrs = res.details[i].kindAttrs;
              temp.kindNames = res.details[i].kindNames;
              temp.attrs = res.details[i].attrs;
              let tempKindNams = temp.kindNames.split(";");
              attrNames = temp.kindNames;
              tempAttrs = temp.attrs.split(";");
           
              this.kindTableHeader = [];
              for (var j = 0; j < tempKindNams.length; j++) {
                temp[tempKindNams[j]] = tempAttrs[j];
                this.kindTableHeader.push({ name: tempKindNams[j] });
                if(!attrNameValue[tempKindNams[j]]){
                   attrNameValue[tempKindNams[j]]=tempAttrs[j];
                }else{
                  if(attrNameValue[tempKindNams[j]].indexOf(tempAttrs[j])<0){
                       attrNameValue[tempKindNams[j]]+=";"+tempAttrs[j];
                  }
                }
              }
              this.kindTableData.push(temp);
            }
          }
          this.setEditor("editorpc", this.form1.detail.detailpc);
          this.setEditor("editorh5", this.form1.detail.detailh5);

          attributeListView(this.form2.kind).then(res => {
            if (res && res.length > 0) {
              for (var i = 0; i < res.length; i++) {
                res[i].checklist = [];
                for(var key in attrNameValue){
                  if(key==res[i].name){
                    res[i].checklist = attrNameValue[key].split(";");
                  }
                }
              }
              this.attrs = res;
            }
          });
        });
      } else {
        this.setEditor("editorpc", this.form1.detail.detailpc);
        this.setEditor("editorh5", this.form1.detail.detailh5);
      }
    });
    productkinds().then(res => {
      this.pkinds = res;
    });
  }
};
</script>